import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Select, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {Facility} from "@/types/resp/facility";
import facilityApi from '@/api/facilityApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import FacilityAdd from "@/pages/facility/FacilityAdd.tsx";
import FacilityView from "@/pages/facility/FacilityView.tsx";
import BuildingSelector from "@/pages/building/BuildingSelector.tsx";
import {getPropertyFacilityStatusText} from "@/utils/dictTranslator.ts";


const FacilityList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '公共设施信息列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<Facility[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Facility>> = await facilityApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Facility> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Facility>['columns'] = [
    {title: '公共设施名称', dataIndex: 'name', key: 'name'},
    {title: '楼栋名称', dataIndex: 'buildingName', key: 'buildingName'},
    {title: '位置', dataIndex: 'location', key: 'location'},
    {title: '最后保养日期', key: 'lastMaintenanceDate', render: (_, record) => (
      <div>{record.lastMaintenanceDate ? record.lastMaintenanceDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '状态', key: 'status', render: (_, record) => (
        <span>
        {(function () {
          if (record.status === 10) return '正常';
          else if (record.status === 20) return '异常';
          else return '未知';
        })()}
      </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [facilityAddVisible, setFacilityAddVisible] = useState(false);
  const [facilityViewVisible, setFacilityViewVisible] = useState(false);
  const [selectedFacilityId, setSelectedFacilityId] = useState(0)
  const [selectedFacility, setSelectedFacility] = useState({})

  const onAdd = () => {
    setSelectedFacilityId(0)
    setFacilityAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedFacilityId(id)
    setFacilityAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      facilityApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: Facility) => {
    setSelectedFacility(record)
    setFacilityViewVisible(true)
  };

  const [buildingSelectorVisible, setBuildingSelectorVisible] = useState(false);
  const findBuilding = () => {
    setBuildingSelectorVisible(true);
  }
  const handleBuildingSelected = (selectedBuilding: { buildingId?: number; buildingName?: string; }) => {
    setBuildingSelectorVisible(false)
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      buildingId: selectedBuilding['buildingId'],
      buildingName: selectedBuilding['buildingName'],
      }));
    }
  };
  const handleCloseBuildingSelector = () => {
    setBuildingSelectorVisible(false)
  };

  const handleCloseFacilityAdd = () => {
    setFacilityAddVisible(false)
  };

  const handleCloseFacilityView = () => {
    setFacilityViewVisible(false)
  };

  useEffect(() => {
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="facilityList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="name" label="公共设施名称">
          <Input maxLength={255} placeholder="请输入公共设施名称"/>
        </Form.Item>
        <Form.Item name="buildingName" label="楼栋名称">
          <Input.Search placeholder="请选择楼栋名称" onSearch={findBuilding} readOnly={true} />
        </Form.Item>
        <Form.Item name="location" label="位置">
          <Input maxLength={255} placeholder="请输入位置"/>
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态" options={[
            { value: 10, label: <span>正常</span> },
            { value: 20, label: <span>异常</span> }
          ]} style={{width: 'var(--select-width)'}} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
      </Form>
      <Table<Facility> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} style={{marginTop: 'var(--container-margin)'}} />
      <BuildingSelector visible={buildingSelectorVisible} onBuildingSelected={handleBuildingSelected} onCloseBuildingSelector={handleCloseBuildingSelector} />
      <FacilityAdd visible={facilityAddVisible} onCloseFacilityAdd={handleCloseFacilityAdd} id={selectedFacilityId} />
      <FacilityView visible={facilityViewVisible} onCloseFacilityView={handleCloseFacilityView} viewRow={selectedFacility} />
    </div>
  );
};

export default FacilityList;
